package com.example.bysj.Dao;
//201902104061徐中堂
import com.example.bysj.domain.authority.Resource;
import com.example.bysj.domain.authority.RoleAssResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
//声明数据库访问类
@Repository("rolePermissionDao")
public class RolePermissionDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ResourceDao resourceDao;

    public List<Resource> getResourceByRoleId(int role_id){
        String sql = "SELECT * FROM roleAssResource WHERE role_id=?";
        List<Resource> resources = jdbcTemplate.query(sql, new Object[]{role_id}, new RowMapper<Resource>() {
            @Override
            public Resource mapRow(ResultSet rs, int rowNum) throws SQLException {
                return resourceDao.getResourceById(rs.getInt("resource_id"));
            }
        });
        return resources;
    }

    public boolean add(RoleAssResource roleAssResource){
        String sql = "INSERT INTO role (id,role_id,resource_id) VALUES(?,?,?)";
        int rowAffected = jdbcTemplate.update(sql,
                roleAssResource.getId(),
                roleAssResource.getRole().getId(),
                roleAssResource.getResource().getId());
        if (rowAffected != 1){
            return false;
        } else {
            return true;
        }
    }
}
